package com.example.victory.common.web;

import com.google.common.base.Predicates;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * swagger配置
 */
@Configuration
public class SwaggerConfig {
    @Value("${springfox.documentation.swagger.title:微服务接口文档}")
    private String title;

    @Value("${springfox.documentation.swagger.author:作者}")
    private String author;

    @Value("${springfox.documentation.swagger.email:developer@cgws.com}")
    private String email;

    @Value("${springfox.documentation.swagger.description:这是使用swagger生成的接口文档}")
    private String description;

    @Value("${swagger.host:}")
    private String host;

    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        if(StringUtils.isNotBlank(host)) {
            docket.host(host);
        }
        return docket
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select() // 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.any())// 对所有api进行监控
                .paths(Predicates.not(PathSelectors.regex("/error.*")))// 错误路径不监控
                .paths(Predicates.not(PathSelectors.regex("/actuator.*")))// actuator路径不监控
                .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(title)
                .contact(new Contact(author, "", email))
                .description(description)
                .termsOfServiceUrl("NO terms of service")
                .version("v1.0")
                .build();
        //.license("The Apache License, Version 2.0")
        //.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
    }
}
